package com.unhz.taigu.controller.system;

import com.unhz.generator.enums.EnumStatus;
import com.unhz.generator.enums.EnumValid;
import com.unhz.generator.pojo.*;
import com.unhz.generator.utils.*;
import com.unhz.generator.vo.UserVo;
import com.unhz.taigu.service.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Date;
import java.util.List;

/**
 * @Author: 沈佳庆
 * @Description: 用户
 * @Date: Created in 下午 2:46 2018/1/24 0024
 * @Modified By:
 */
@Controller
@RequestMapping("/user")
public class UserController{

    private Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private UserDictService userDictService;

    @Autowired
    private AreaDictService areaDictService;

    @Autowired
    private ProductionRangeService productionRangeService;

    @Autowired
    private KeyService keyService;

    @Autowired
    private SysRolePermissionService sysRolePermissionService;


    /**
     * 分页查询
     * @param model
     * @param pageNo 页数
     * @param keywords 关键词
     * @return
     */
    @RequestMapping("/findAllUser")
    @RequiresPermissions("user:find")
    public String findAllPermission(Model model,
                                    @RequestParam(value = "adminId",defaultValue = "",required = false)Integer adminId,
                                    @RequestParam(value = "roleId",defaultValue = "",required = false)Integer roleId,
                                    @RequestParam(value = "pageNo",defaultValue = "1",required = false)String pageNo,
                                    @RequestParam(value = "keywords",defaultValue = "",required = false)String keywords){
        //List<Permission> permissions = permissionService.selectAllPermission();
        Page<User> page = userService.selectPageUser(pageNo,PageSize.pageSize,keywords,adminId,roleId);
        int counts = sysRolePermissionService.selectByroleId(roleId);
        model.addAttribute("counts",counts);
        model.addAttribute("page",page);
        model.addAttribute("keywords",keywords);
        return "system/user/index.jsp";
    }



    /**
     * 删除某一个用户
     * @param userId
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(@RequestParam("userId")Integer userId){
        logger.info("id为"+userId);
        try {
            userService.deleteById(userId);
        }catch (Exception e){
            e.printStackTrace();
            return JsonResult.failure(e.getMessage());
        }
        return JsonResult.success();
    }

    /**
     * 查看某一个用户的详情
     * @param userId
     * @param model
     * @return
     */
    @RequestMapping("/details")
    @RequiresPermissions("user:find")
    public String details(@RequestParam("userId")Integer userId,  Model model){

        UserVo user = userService.findUserById(userId);
        model.addAttribute("user",user);
        return "system/user/details.jsp";
    }


    /**
     * 跳转到新增用户页面
     * @param model
     * @return
     */
    @RequestMapping("/addUser")
    @RequiresPermissions("user:add")
    public String addUser(Model model){
        List<UserDict> userDict = userDictService.findJobType();
        List<UserDict> rangeList = userDictService.findRangeType();
        List<AreaDict> areaDict = areaDictService.findArea();
        model.addAttribute("userDict",userDict);
        model.addAttribute("rangeList",rangeList);
        model.addAttribute("areaDict",areaDict);
        return "system/user/add.jsp";
    }

    /**
     * 新增用户
     * @return
     */
    @RequestMapping("/insert")
    public String insert(Model model,User user, @RequestParam("type") String type,
                                                @RequestParam("adminId") Integer adminId,
                                                @RequestParam("adminName") String adminName,
                                                @RequestParam("roleId") Integer roleId){
        Key key = keyService.selectKey();
        int userKey = key.getUserKey();
        user.setSource(0);
        if(userKey==1){
            user.setValid(EnumValid.ENABLED.getIndex());
            user.setStatus(EnumStatus.PASS.getIndex());
        }else{
            user.setValid(EnumValid.FIRST_ENABLED.getIndex());
            user.setStatus(EnumStatus.CHECKING.getIndex());
        }
        user.setAdminId(adminId);
        user.setUserName(user.getUserName().replaceAll(" ", ""));
        List<User> list = userService.selectAllUser();
        for(User users:list){
            String userPhone = user.getUserPhone().replaceAll(" ","");
            Boolean b = users.getUserPhone().contains(userPhone);
            if(b==true){
                model.addAttribute("error","此手机号已被注册");
                return "system/user/add.jsp";
            }
        }
        user.setUserPhone(user.getUserPhone().replaceAll(" ",""));
        user.setCompanyName(user.getCompanyName().replaceAll(" ",""));
        user.setCompanyAddress(user.getCompanyAddress().replaceAll(" ",""));
        user.setStorageAddress(user.getStorageAddress().replaceAll(" ",""));
        user.setCreateTime(new Date());
        user.setCreateBy(adminName);
        user.setUserPassword(MD5.MD5Encode("123456"));
        userService.insert(user);
        Integer id = user.getId();
        System.out.println(id);
        String [] strs = type.split(",");
        ProductionRange productionRange = null;
        for(int i=0,len=strs.length;i<len;i++){
            productionRange = new ProductionRange();
            productionRange.setUserId(id);
            productionRange.setCreateTime(new Date());
            productionRange.setProductionRange(strs[i]);
            productionRangeService.insert(productionRange);
        }
        return "redirect:findAllUser?adminId="+adminId+"&roleId="+roleId;
    }

    /**
     * 跳转到修改页面
     * @param userId
     * @param model
     * @return
     */
    @RequestMapping("/toUpdate")
    @RequiresPermissions("user:update")
    public String toUpdate(Model model, @RequestParam("userId")Integer userId){
        User user=userService.selectById(userId);
        //查询所有类型职位
        List<UserDict> userDict = userDictService.findJobType();
        //查询所有生产类型（男鞋，女鞋，童鞋)
        List<UserDict> rangeList = userDictService.findRangeType();
        //查询该用户的生产类型
        List<ProductionRange> productionRanges = productionRangeService.selectByUserId(userId);
        //区域字典表-省
        List<AreaDict> areaDict = areaDictService.findArea();
        //企业 区域字典表-市
        List<AreaDict> areaDictCCitys=areaDictService.findCity(user.getCompanyProvince());
        //企业 区域字典表-区
        List<AreaDict> areaDictCCounties=areaDictService.findCountry(user.getCompanyCity());
        //仓库 区域字典表-市
        List<AreaDict> areaDictSCitys=areaDictService.findCity(user.getStorageProvince());
        //仓库 区域字典表-区
        List<AreaDict> areaDictSCounties=areaDictService.findCountry(user.getStorageCity());

        for(UserDict userDict1:rangeList){
            userDict1.setChange("0");
        }
        //状态设为选中
        for(ProductionRange productionRange:productionRanges){
            for(UserDict userDict1:rangeList){
                if(userDict1.getName().equals(productionRange.getProductionRange())){
                    userDict1.setChange("1");
                }
            }
        }
        model.addAttribute("userDict",userDict);   //用户字典
        model.addAttribute("rangeList",rangeList); //生产范围列表
        model.addAttribute("areaDict",areaDict);  //区域字典列表-省
        model.addAttribute("areaDictCCitys",areaDictCCitys);
        model.addAttribute("areaDictCCounties",areaDictCCounties);
        model.addAttribute("areaDictSCitys",areaDictSCitys);
        model.addAttribute("areaDictSCounties",areaDictSCounties);

        model.addAttribute("user",user);         //要修改的用户
        return "system/user/update.jsp";
    }

    /**
     * 执行禁用或者启用
     * @param userId
     * @param isenable
     * @return
     */
    @RequestMapping("/isenable")
    @ResponseBody
    @RequiresPermissions("user:isenable")
    public JsonResult isenable(@RequestParam("userId")Integer userId,
                               @RequestParam("isenable")Integer isenable,
                               @RequestParam("adminName")String adminName){
        String index = userService.updateIsenable(userId, isenable,adminName);
        if("success".equals(index)){
            return JsonResult.success("操作成功");
        }
        return JsonResult.failure("操作失败");
    }

    /**
     * 执行审核通过不通过
     * @param userId
     * @param examine
     * @return
     */
    @RequestMapping("/examine")
    @ResponseBody
    @RequiresPermissions("user:examine")
    public JsonResult examine(@RequestParam("userId")Integer userId,
                               @RequestParam("examine")Integer examine,
                              @RequestParam("adminName")String adminName){
        String index = userService.updateExamine(userId, examine,adminName);
        if("success".equals(index)){
            return JsonResult.success("操作成功");
        }
        return JsonResult.failure("操作失败");
    }

    /**
     * 修改用户
     * @param user
     * @return
     */
    @RequestMapping("/update")
    public String updateUser(User user, @RequestParam(value="type")String type,
                             @RequestParam("adminId") Integer adminId,
                             @RequestParam("roleId") Integer roleId){
             int flag = userService.updateUser(user,type);
              if(flag>0){
               return "redirect:findAllUser?adminId="+adminId+"&roleId="+roleId;
              }
        return "system/user/update.jsp";
    }

    /**
     * 一键审核
     * @return
     */
    @RequestMapping("/keyPass")
    @ResponseBody
    public JsonResult keyPass(){
        User user = new User();
        user.setValid(1);
        user.setStatus(2);
        userService.keyPass(user);
        Key key = new Key();
        key.setId(1);
        key.setUserKey(1);
        keyService.updateKey(key);
        return JsonResult.success("操作成功");
    }

    /**
     * 取消一键审核
     * @return
     */
    @RequestMapping("/noKeyPass")
    @ResponseBody
    public JsonResult noKeyPass(){
        Key key = new Key();
        key.setId(1);
        key.setUserKey(0);
        keyService.updateKey(key);
        return JsonResult.success("操作成功");
    }

    /**
     * 查询一键审核标识符
     * @return
     */
    @RequestMapping("/selectKey")
    @ResponseBody
    public Key selectKey(){
        Key key = keyService.selectKey();
        return key;
    }


}
